var config = require('./config.js')

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function authentication(appId,appKey,deviceId,HttpMothod, HttpPath) {
    var SecretAccessKey = appKey;
    var SHA1 = new Hashes.SHA1(),
    stringToSign = HttpMothod.toUpperCase() + '\n\n' + HttpPath + '\n' + deviceId,
    signature = SHA1.b64_hmac(SecretAccessKey, stringToSign);
    return 'ZHAO ' + appId + ':' + signature;
};

function dateFormatYear(timestamp) {
    var jsdate;
    if (typeof timestamp == 'string' && timestamp.split('-').length > 1 && timestamp.split('T').length > 1) {
        jsdate = new Date((+new Date(timestamp.replace(/(\d+:?)\-(\d+)\-(\d+)T(.*)Z/,'$2/$3/$1 $4'))) + 8*60*60*1000);
        // jsdate = new Date((+new Date(timestamp.replace(/(\d+:?)\-(\d+)\-(\d+)T(.*)Z/,'$2/$3/$1 $4'))));
    } else if (typeof timestamp == 'string' && timestamp.split('-').length > 1 && timestamp.split('T').length == 1) {
        jsdate = new Date(timestamp.replace(/(\d+:?)\-(\d+)\-(\d+)(.*)/,'$2/$3/$1 $4'));
    } else {
        jsdate = timestamp ? new Date(timestamp) : new Date();
    }
    var now = Date.parse(new Date());
    var nowYear = new Date(now).getFullYear();
    var yearTime = Date.parse(new Date(nowYear + '-01-01'));
    if(jsdate.getFullYear() < new Date(now).getFullYear()){
        return dateFormat(timestamp, 'Y.m.d');
    } else{
        return dateFormat(timestamp, 'Y.m.d H:i');
    }
}

function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
};

const base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64DecodeChars = new Array(
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
        -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
/**
 * base64加密
 */
function base64encode(str) {
    var out, i, len;
    var c1, c2, c3;

    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}

/**
 * base64 解密
 */
function base64decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;

    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        /* c1 */
        do {
            c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while (i < len && c1 == -1);
        if (c1 == -1)
            break;

        /* c2 */
        do {
            c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while (i < len && c2 == -1);
        if (c2 == -1)
            break;

        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

        /* c3 */
        do {
            c3 = str.charCodeAt(i++) & 0xff;
            if (c3 == 61)
                return out;
            c3 = base64DecodeChars[c3];
        } while (i < len && c3 == -1);
        if (c3 == -1)
            break;

        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

        /* c4 */
        do {
            c4 = str.charCodeAt(i++) & 0xff;
            if (c4 == 61)
                return out;
            c4 = base64DecodeChars[c4];
        } while (i < len && c4 == -1);
        if (c4 == -1)
            break;
        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}

//对字符串进行加密
function compileStr(code){
    var c=String.fromCharCode(code.charCodeAt(0)+code.length);
    for(var i=1;i<code.length;i++){
    c+=String.fromCharCode(code.charCodeAt(i)+code.charCodeAt(i-1));
    }
    return escape(c);
}

//字符串进行解密
function uncompileStr(code){
   code=unescape(code);
   var c=String.fromCharCode(code.charCodeAt(0)-code.length);
   for(var i=1;i<code.length;i++){
   c+=String.fromCharCode(code.charCodeAt(i)-c.charCodeAt(i-1));
   }
   return c;
}

const Suan = {
    encode: (data) => {
        return base64encode(compileStr(data).replace(/%/g, '\\'));
    },
    decode: (data) => {
        return uncompileStr(base64decode(data).replace(/\\/g, '%'));
    },
    getStorage: (data) => {
        if(wx.getStorageSync(data)){
            return JSON.parse(Suan.decode(wx.getStorageSync(data))) || ''
        }
        return ""
    }
}

function changeNum(num) {
    var num1 = parseFloat(num);
    if (!isNaN(num1)) {
        num1 = Math.round(num1*100)/100;
        var str = num1.toString();
        var rs = str.indexOf('.');
        if (rs < 0) {
            rs = str.length;
            str += '.';
        }
        while (str.length <= rs + 2) {
            str += '0';
        }
        return str;
    }
}
/**
 * 价格过滤器
 */
function formatPrice(s,n) {
    if(!s) s = 0;
    var m = parseFloat(s) < 0 ? '-' : '';
    n = (!n || (n >= 0 && n <= 20)) ? n : 2;
    s = parseFloat((Math.abs(s) + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
    var l = s.split('.')[0].split('').reverse(),
        r = s.split('.')[1] || '';
    var t = '',
        i;
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 === 0 && (i + 1) != l.length ? ',' : '');
    }
    return m + t.split('').reverse().join('') + (r ? ('.' + r) : '');
};
/**
 * 点赞喜欢数量过滤器
 */
function formatLikeNum(num) {
    if(num >= 10000){
        num = Math.floor(num / 10000 * 10) / 10 + '万'
    } else if(num >= 1000){
        num = Math.floor(num / 1000 * 10) / 10 + 'k'
    }
    return num;
};

module.exports = {
    authentication: authentication,
    Suan: Suan,
    changeNum: changeNum,
    formatPrice: formatPrice,
    formatLikeNum: formatLikeNum
}
